#!/usr/bin/python
# -*- coding: utf-8 -*-
from bot import WebChatBot
import time, os, sys

import simplejson as json

from config import BOT, BOT_NICK

class IkitoBot(WebChatBot):

    def process_conf_message(self, nick, text, **kwargs):
        if text and not nick==BOT_NICK:
            self.log.info(u'See groupchat message from {0}: {1}'.format(nick, text))

        if BOT_NICK in text and ("hi" in text.lower() or u"привет" in text.lower()):
            self.send_to_conference(u"Привет, {0}".format(nick))
    # self.log_conference_message(nick, text) #should run in parent class
        pass
    def process_incoming_message(self, from_user, text, **kwargs):
        self.send_to_conference(text)
        self.send_to_user(from_user, u"Текст отправлен: "+text)
        pass

    def process_task(self, msg):
        self.log.info('process_task called')
        try:
            task = json.loads(msg)
            print 'got correct task'
            self.log.info('got correct task')
        except json.decoder.JSONDecodeError as e: 
            task = None
            self.log.warning('unable to decode task {0}. error: {1}'.format(msg, e))

        if task: action = task.get('action', None)
        else: action = None

        if action == 'vote':
            jabber = task.get('jabber', None)
            track_id = task.get('track_id', None)
            vote = task.get('vote', None)
            if jabber and track_id and vote:
                #s = u"user {0} votes {1} for #{2}".format(jabber, vote, track_id)
                vote_text = vote+' '+str(track_id)
                self.send_to_user('robot@tmradio.net', vote_text )
                return
        if action == 'chat':
            from_nickname = task.get('from_nickname', None) or task.get('nickname', None) or task.get('from_user', None)
            text = task.get('text', None)
            if from_nickname and text:
                self.send_to_conference(u"{0} ({1})".format(text, from_nickname))
        if action == 'direct':
            jid = task.get('jid', None)
            text = task.get('text', None)
            if jid and text:
                self.send_to_user(jid, text)
        if not action:
            self.send_to_conference(msg)
        pass

if __name__ == "__main__":
    print "__main__: create bot"
    ikitobot = IkitoBot(*BOT)
    print "__main__: run bot"
    ikitobot.run()
    print "__main__: the end..."
    exit()
